/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.shop.web;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.alibaba.fastjson.JSONObject;
import com.jeeplus.modules.api.utils.WohuiEntity;
import com.jeeplus.modules.api.utils.WohuiUtils;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.msg.service.MsgService;
import com.jeeplus.modules.shop.entity.Shop;
import com.jeeplus.modules.shop.service.ShopService;

/**
 * 实体商家Controller
 * @author lixinapp
 * @version 2019-10-16
 */
@Controller
@RequestMapping(value = "${adminPath}/shop/shop")
public class ShopController extends BaseController {

	@Autowired
	private ShopService shopService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private MsgService msgService;

	@ModelAttribute
	public Shop get(@RequestParam(required=false) String id) {
		Shop entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = shopService.get(id);
		}
		if (entity == null){
			entity = new Shop();
		}
		return entity;
	}
	
	/**
	 * 实体商家列表页面
	 */
	@RequiresPermissions("shop:shop:list")
	@RequestMapping(value = {"list", ""})
	public String list(Shop shop, Model model) {
		model.addAttribute("shop", shop);
		return "modules/shop/shopList";
	}
	
		/**
	 * 实体商家列表数据
	 */
	@ResponseBody
	@RequiresPermissions("shop:shop:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Shop shop, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Shop> page = shopService.findPage(new Page<Shop>(request, response), shop); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑实体商家表单页面
	 */
	@RequiresPermissions(value={"shop:shop:view","shop:shop:add","shop:shop:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Shop shop, Model model) {
		model.addAttribute("shop", shop);
		return "modules/shop/shopForm";
	}

	/**
	 * 保存实体商家
	 */
	@ResponseBody
	@RequiresPermissions(value={"shop:shop:add","shop:shop:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Shop shop, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(shop);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		shopService.save(shop);//保存
		j.setSuccess(true);
		j.setMsg("保存实体商家成功");
		return j;
	}
	/**
	 * 审核实体商家
	 */
	@ResponseBody
	@RequiresPermissions(value="shop:shop:edit")
	@RequestMapping(value = "audit")
	public AjaxJson audit(Shop shop, String type, String reason) throws Exception{
		AjaxJson j = new AjaxJson();
//		if (!"1".equals(shop.getAuditState())) {
//			j.setSuccess(false);
//			j.setMsg("只能操作待审核状态的店铺");
//			return j;
//		}
		Member member = shop.getMember();
		if (member != null && member.getTxopenid()==null) {
//			j.setMsg("该商家没有openid,无法通过审核");
			String msg = "请关注我惠云店公众号---点击左下角的商城首页---进入到我的（没有登录的需要登录）--点击右上角的齿轮--点击 商家微信提现绑定";
			msgService.insert(shop.getMember(), "系统消息", "您的实体店铺入驻申请被需要商家微信提现绑定，" + msg);
//			return j;
		}
		if (Double.valueOf(shop.getPtrebate())<=0.0) {
			j.setMsg("该商家平台返利标准不符合,请重新填写");
			String msg = "该商家平台返利标准不符合,请重新填写";
			shop.setAuditState("3");
			shop.setAuditDate(new Date());
			shopService.save(shop);
			msgService.insert(shop.getMember(), "系统消息", "您的实体店铺入驻申请被拒绝，原因：" + msg);
			return j;
		}

		shop.setAuditState(type);
		shop.setAuditDate(new Date());
		shopService.save(shop);//保存
		if ("2".equals(type)) {
			String sqtype="SQ";
			String paymoney="0";
			if("0".equals(shop.getXhtype())){
				sqtype= "SQXHBT";
				paymoney=shop.getPaymoney();
			}
			if("2".equals(shop.getXhtype())){
				sqtype= "SQPFDPDL";
				paymoney=shop.getPaymoney();
			}
			// 调用三方
			List<WohuiEntity> list = Lists.newArrayList();
			list.add(new WohuiEntity("Type", sqtype));
			list.add(new WohuiEntity("ShopName", shop.getTitle()));
			list.add(new WohuiEntity("CardGUID", shop.getMember().getId()));
			list.add(new WohuiEntity("RealName", shop.getUsername()));
			list.add(new WohuiEntity("Phone", shop.getPhone()));
			list.add(new WohuiEntity("SignGUID", shop.getInvite().getId()));
//			list.add(new WohuiEntity("SignRealName", shop.getInviteName()));
			list.add(new WohuiEntity("PayGUID", ""));
			//list.add(new WohuiEntity("PayRealName", ""));
			list.add(new WohuiEntity("UnionCode", shop.getShopCode()));
			//list.add(new WohuiEntity("GoodsCode", store.getProductCode()));
			list.add(new WohuiEntity("Fee", "0"));
			list.add(new WohuiEntity("FeeYear", "1"));
			list.add(new WohuiEntity("PayMoney", paymoney));
			list.add(new WohuiEntity("Remark", ""));
			JSONObject object = WohuiUtils.send(WohuiUtils.SupplierOpen, list);
			if (!"0000".equals(object.getString("respCode"))) {
				logger.error("附近商圈调用会员系统开通供应商失败：" + object.getString("respMsg"));
			}
		}
		// 拒绝后发消息
		if ("3".equals(type) && StringUtils.isNotBlank(reason)) {
			msgService.insert(shop.getMember(), "系统消息", "您的实体店铺入驻申请被拒绝，原因：" + reason);
		}
		j.setSuccess(true);
		j.setMsg("审核成功");
		return j;
	}
	/**
	 * 审核实体商家简介
	 */
	@ResponseBody
	@RequiresPermissions(value="shop:shop:edit")
	@RequestMapping(value = "auditShow")
	public AjaxJson auditShow(Shop shop, String type) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!"0".equals(shop.getShowState())) {
			j.setSuccess(false);
			j.setMsg("只能操作待审核状态的店铺");
			return j;
		}
		shop.setShowState(type);
		shopService.save(shop);//保存
		j.setSuccess(true);
		j.setMsg("审核成功");
		return j;
	}
	/**
	 * 冻结解冻实体商家
	 */
	@ResponseBody
	@RequiresPermissions(value="shop:shop:edit")
	@RequestMapping(value = "updateState")
	public AjaxJson updateState(Shop shop, String type) throws Exception{
		AjaxJson j = new AjaxJson();
		if (StringUtils.isNotBlank(shop.getId())) {
			shop.setState(type);
			shopService.save(shop);//保存
		}
		j.setSuccess(true);
		j.setMsg("操作成功");
		return j;
	}
	
	/**
	 * 删除实体商家
	 */
	@ResponseBody
	@RequiresPermissions("shop:shop:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Shop shop) {
		AjaxJson j = new AjaxJson();
		shopService.delete(shop);
		j.setMsg("删除实体商家成功");
		return j;
	}
	
	/**
	 * 批量删除实体商家
	 */
	@ResponseBody
	@RequiresPermissions("shop:shop:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			shopService.delete(shopService.get(id));
		}
		j.setMsg("删除实体商家成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("shop:shop:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Shop shop, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "实体商家"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Shop> page = shopService.findPage(new Page<Shop>(request, response, -1), shop);
    		new ExportExcel("实体商家", Shop.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出实体商家记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("shop:shop:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Shop> list = ei.getDataList(Shop.class);
			for (Shop shop : list){
				try{
					shopService.save(shop);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条实体商家记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条实体商家记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入实体商家失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入实体商家数据模板
	 */
	@ResponseBody
	@RequiresPermissions("shop:shop:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "实体商家数据导入模板.xlsx";
    		List<Shop> list = Lists.newArrayList(); 
    		new ExportExcel("实体商家数据", Shop.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }

}